package com.suke.czx.modules.file.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.CodeConstant;
import com.suke.czx.common.utils.FieldConstant;
import com.suke.czx.common.utils.R;
import com.suke.czx.modules.file.entity.File;
import com.suke.czx.modules.file.service.FileService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 应用模块名称: 文件
 * 代码描述: 文件控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/09/07 23:22
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/file")
@AllArgsConstructor
@Api(value = "FileController", tags = "文件管理")
public class FileController extends AbstractController {

    private final FileService fileService;

    /**
     * 分页查询文件列表
     * @param params 查询参数
     * @return VO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:file:list')")
    public R list(@RequestParam Map<String, Object> params) {
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
            return R.error("缺少分页信息");
        }
        // 查询列表数据
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        if (params.size() > 2){
            queryWrapper.like(!StrUtil.isBlankIfStr(params.get(FieldConstant.FILE_NAME)), StrUtil.toUnderlineCase(FieldConstant.FILE_NAME), params.get(FieldConstant.FILE_NAME));
        }
        IPage<File> customerPage = fileService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, customerPage.getTotal())).setData(Optional.ofNullable(customerPage.getRecords()).orElse(Lists.newArrayList()));
    }

    /**
     * 根据文件ids查询文件数据集
     * @param fileIds 文件ids
     * @return VO
     */
    @RequestMapping(value = "/ids", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:expressFile:ids') or hasRole('but:contractFile:ids') or hasRole('but:incomeFile:ids') or hasRole('but:taskFile:ids')")
    public R getFileByIds(@NotBlank(message = "文件ids不能为空") String fileIds) {
        // 根据文件ids查询文件url
        List<File> fileList = fileService.getFileByIds(fileIds);
        return R.ok().setData(fileList);
    }

    /**
     * 保存文件
     * @param file 文件
     * @param note 备注
     * @return VO
     */
    @SysLog("保存文件")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:expressFile:save') or hasRole('but:contractFile:save') or hasRole('but:incomeFile:save') or hasRole('but:taskFile:save')")
    public R save(@NotNull(message = "文件不能为空") MultipartFile file, String note) {
        File f = new File();
        f.setFileName(file.getOriginalFilename());
        f.setFileUrl(fileService.uploadFile(file));
        f.setNote(note);
        f.setCreator(getUserId());
        f.setCreateTime(new Date());
        fileService.save(f);
        // 查询保存记录
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        queryWrapper.eq(StrUtil.toUnderlineCase(FieldConstant.FILE_URL), f.getFileUrl());
        File existsFile = fileService.getOne(queryWrapper);
        return R.ok().setData(existsFile);
    }

    /**
     * 更新文件
     * @param fileId 文件编码
     * @param file 文件
     * @param note 备注
     * @return VO
     */
    @SysLog("更新文件")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:expressFile:update') or hasRole('but:contractFile:update') or hasRole('but:incomeFile:update') or hasRole('but:taskFile:update')")
    public R update(@NotNull(message = "文件编码不能为空") Long fileId, @NotNull(message = "文件不能为空") MultipartFile file, String note) {
        File f = new File();
        f.setFileId(fileId);
        f.setFileName(file.getOriginalFilename());
        f.setFileUrl(fileService.uploadFile(file));
        f.setNote(note);
        f.setUpdater(getUserId());
        f.setUpdateTime(new Date());
        fileService.updateById(f);
        // 查询更新记录
        File existsFile = fileService.getById(fileId);
        return R.ok().setData(existsFile);
    }

    /**
     * 删除文件
     * @param fileId 文件编码
     * @return VO
     */
    @SysLog("删除文件")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:expressFile:delete') or hasRole('but:contractFile:delete') or hasRole('but:incomeFile:delete') or hasRole('but:taskFile:delete')")
    public R delete(@NotNull(message = "文件编码不能为空") Long fileId) {
        return fileService.updateDelFile(fileId, getUserId());
    }

}
